function Iok = txtWriteData(filena,head,data)
%txtWriteData - header and data write to a txt file
%
%       Iok = txtWriteData(FILENA,HEAD,DATA)
% 
% This function provides the header HEAD (as a char array, if the header
% exists; if the header does not exist, it is HEAD = []) and the numerical
% data array DATA from the file FILENA.
% If FILENA is undefined or empty, the filename can be interactively managed.

% G. Teza, 2022 

if nargin < 2
    head = [];
end
if nargin < 1 || isempty(filena)
    [fily1,pathy1] = uiputfile(...
        {'*.txt','(*.txt)';'*.dat','(*.dat)';'*.asc','(*.asc)';'*.mom','(*.mom)'},...
        'ASCII FILE');
    if isnumeric(fily1) || isnumeric(pathy1)
        filena = []; 
    else
        filena = fullfile(pathy1,fily1);
    end
end
if isempty(filena)
    Iok = false;
    return
end

if isempty(head)
    nrhead = 0;
else
    nrhead = size(head,1);
end
ncdata = size(data,2);

fidh = fopen(filena,'w+');
if nrhead > 0
    for k = 1:nrhead
        fprintf(fidh,'%s\n',head{k});
    end
end
fclose(fidh);

strWrite = repmat('%f\t',1,ncdata);
strWrite(end) = 'n'; % return instead of tabulation after the last column
fidd = fopen(filena,'a+');
fprintf(fidd,strWrite,data');
fclose(fidd);

Iok = true;